package com.wenkang.stu.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.wenkang.stu.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Slf4j
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtils {
    @Autowired
    SmsProperties smsProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "sms:phone:";
    private static final long SMS_MIN_INTERVAL_IN_MILLIS = 60000;

    public void sendSms(String phoneNumber, String signName, String codeTemplate, String templateParam) {
        try {
            String key = KEY_PREFIX + phoneNumber;
            // 按照手机号码限流
            // 读取redis数据，（如果redis数据还未过期，阻止发送短信）
            String lastTime = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(lastTime)) {
                Long last = Long.valueOf(lastTime);
                if (System.currentTimeMillis() - last < SMS_MIN_INTERVAL_IN_MILLIS) {
                    log.info("[短信服务] 发送信息频率过高，被拦截， 手机号码:{}", phoneNumber);
                    return;
                }
            }
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", phoneNumber);
            request.putQueryParameter("SignName", signName);
            request.putQueryParameter("TemplateCode", codeTemplate);
            request.putQueryParameter("TemplateParam", templateParam);
            CommonResponse response = client.getCommonResponse(request);
            if (response.getHttpStatus() != 200) {
                log.info("[短信服务] 发送短信失败，phoneNumber：{}， result：{}", phoneNumber, response.getData());
            }
            // 发送短信成功后，写入redis,存入当前时间，有效时间1 单位分钟。
            redisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis()), 1, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("[短信服务] 发送短信异常，phoneNumber：{}， exception：{}", phoneNumber, e);
        }
    }
}
